import random

# 存储历史经验数据
'''
经验回放缓冲区是深度强化学习中常用的组件，特别是在像深度Q网络（DQN）这样的离策略方法中。
它用于存储智能体在环境中交互的经验（状态、动作、奖励、下一个状态、是否完成），
并在训练过程中随机采样这些经验，以打破连续经验之间的相关性。
'''
class ReplayMemory(object):
    def __init__(self, max_size):
        self.max_size = max_size
        self.buffer = []

    def push(self, state, action, reward, next_state, done):
        experience = (state, action, reward, next_state, done)
        self.buffer.append(experience)

    def sample(self, batch_size):
        state_batch = []
        action_batch = []
        reward_batch = []
        next_state_batch = []
        done_batch = []

        batch = random.sample(self.buffer, batch_size)

        for experience in batch:
            state, action, reward, next_state, done = experience
            state_batch.append(state)
            action_batch.append(action)
            reward_batch.append(reward)
            next_state_batch.append(next_state)
            done_batch.append(done)

        return (state_batch, action_batch, reward_batch, next_state_batch, done_batch)

    def truncate(self):
        self.buffer = self.buffer[-self.max_size:]

    def __len__(self):
        return len(self.buffer)